﻿namespace ReplayDataFile
{
    using System;
    using System.Collections.Generic;

    public class RecordUnZipper
    {
        private static byte[] bitMask = new byte[] { 1, 2, 4, 8, 0x10, 0x20, 0x40, 0x80 };
        private Dictionary<int, DataRecord> lastFullRecordDict = new Dictionary<int, DataRecord>();

        public void UnZip(DataRecord rec)
        {
            DataRecord record = null;
            if (this.lastFullRecordDict.ContainsKey(rec.DataType))
            {
                record = this.lastFullRecordDict[rec.DataType];
            }
            this.lastFullRecordDict[rec.DataType] = rec;
            int zipType = rec.ZipType;
            if ((zipType != 0) && (record != null))
            {
                if (zipType == 1)
                {
                    rec.DataBuffer = record.DataBuffer;
                }
                else
                {
                    byte[] buffer;
                    byte[] dataBuffer;
                    int num3;
                    int num4;
                    if (zipType == 2)
                    {
                        buffer = new byte[record.DataBuffer.Length];
                        Buffer.BlockCopy(record.DataBuffer, 0, buffer, 0, buffer.Length);
                        dataBuffer = rec.DataBuffer;
                        int num2 = dataBuffer.Length / 3;
                        num3 = 0;
                        for (num4 = 0; num4 < num2; num4++)
                        {
                            int index = dataBuffer[num3] + (dataBuffer[num3 + 1] << 8);
                            buffer[index] = dataBuffer[num3 + 2];
                            num3 += 3;
                        }
                        rec.DataBuffer = buffer;
                    }
                    else if (zipType == 3)
                    {
                        buffer = new byte[record.DataBuffer.Length];
                        Buffer.BlockCopy(record.DataBuffer, 0, buffer, 0, buffer.Length);
                        dataBuffer = rec.DataBuffer;
                        num3 = (buffer.Length + 7) / 8;
                        for (num4 = 0; num4 < buffer.Length; num4++)
                        {
                            int num6 = num4 / 8;
                            int num7 = num4 % 8;
                            if ((dataBuffer[num6] & bitMask[num7]) != 0)
                            {
                                buffer[num4] = dataBuffer[num3++];
                            }
                        }
                        rec.DataBuffer = buffer;
                    }
                }
                rec.ZipType = 0;
            }
        }
    }
}

